<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Admin\BaseController;
use App\Models\Admin\Menu;
use App\Models\Admin\Permission;
use Illuminate\Http\Request;

class MenuController extends BaseController
{
    public function toCreate()
    {
        $pmenus = Menu::where('parent_id', 0)->get();
        $menu = new Menu();
        return view('admin.auth.menu.menu',compact('menu','pmenus'));
    }
    public function toEdit(menu $menu)
    {
        $pmenus = Menu::where('parent_id', 0)->get();
        return view('admin.auth.menu.menu', compact('menu','pmenus'));
    }

    public function save(Request $request)
    {
        if($request->input('id')){
            $menu = Menu::find($request->input('id'));
            $menu->title = $request->input('title');
            $menu->parent_id = $request->input('parent_id');
            $menu->icon = $request->input('icon');
            $menu->uri = $request->input('uri');
        }else{
            $menu = new Menu();
            $menu->title = $request->input('title');
            $menu->parent_id = $request->input('parent_id');
            $menu->icon = $request->input('icon');
            $menu->uri = $request->input('uri');
        }
        $perms = Permission::where('url','like','%'.$request->input('uri').'%')->get();
        if($perms){
            $pms = '';
            foreach($perms as $perm){
                $pms .= $perm->name.'|';
            }
            $pms = substr($pms,0,strlen($pms)-1);
            $menu->permission_name = $pms;
        }
        $ret = $menu->save();

        if($ret){
            return $this->success('提交成功', route('admin-menus'));
        }else{
            return $this->error();
        }
    }

    public function menus()
    {
        $menus = Menu::orderBy('parent_id','asc')->get();
        $list = array();
        foreach ($menus as $menu){
            if($menu->parent_id == 0){
                $list[$menu->id]['id'] = $menu->id;
                $list[$menu->id]['title'] = $menu->title;
                $list[$menu->id]['uri'] = $menu->uri;
                $list[$menu->id]['icon'] = $menu->icon;
                $list[$menu->id]['parent_id'] = $menu->parent_id;
            }else{
                $list[$menu->parent_id]['items'][] = array('id'=>$menu->id,'title'=>$menu->title,'uri'=>$menu->uri,'icon'=>$menu->icon,'parent_id'=>$menu->parent_id);
            }
        }
        $pmenus = Menu::where('parent_id', 0)->get();
        $menu = new Menu();
        return view('admin.auth.menu.menus', compact('list','pmenus', 'menu'));
    }

    public function delete(Menu $menu){
        $ret = $menu->delete();
        if($ret){
            return $this->success('删除成功');
        }else{
            return $this->error();
        }
    }
}
